import { _decorator, Component, Vec3, Prefab, instantiate, Vec2, log, v2, Graphics, Color, color } from 'cc';
import { Ball, BallColor } from './ball';
import EventMgr from './EventManager';
import { EventType } from './enumType';
import { PathManager } from './PathManager';
const { ccclass, property } = _decorator;

export const MoveSpeed = 0.3;

@ccclass('BallChainManager')
export class BallChainManager extends Component {
    @property(Prefab) ballPrefab:Prefab = null

    private graphics: Graphics | null = null;
    // 当前球链中的小球数组
    private ballChain: Ball[] = [];
    private ballNumber = 6; // 小球数量

    protected onLoad(): void {
        
        EventMgr.Instance.on(EventType.play,this.init,this)
        EventMgr.Instance.on(EventType.insert,this.insertBallIntoChain,this)
    }

    init() {
        this.graphics = this.getComponent(Graphics);
        // 初始化球链
        this.schedule(() => {
            this.addBallToChain();
        }, MoveSpeed, this.ballNumber);
    }
    
    public insertBallIntoChain(shootBall: Ball, targetBall: Ball) {
        let insertIndex = this.ballChain.indexOf(targetBall);
        log("数组下标 :", insertIndex);
        let targetIndex = targetBall.TargetIndex;
        log("目标下标 :", targetIndex);
        // 处理边界条件
        let posBefore = PathManager.equidistantPoints[targetIndex - 1];
        const pos = PathManager.equidistantPoints[targetIndex];
        let posAfter = PathManager.equidistantPoints[targetIndex + 1];
        const { index: headIndex, ratio: headRatio } = this.headProgress;
        let lenBefore = Infinity;
        let lenAfter = Infinity;

        posBefore = new Vec2(
            posBefore.x + (pos.x - posBefore.x) * headRatio,
            posBefore.y + (pos.y - posBefore.y) * headRatio
        );
        lenBefore = Vec2.distance(posBefore, new Vec2(shootBall.node.position.x, shootBall.node.position.y));
        
        posAfter = new Vec2(
            posAfter.x + (pos.x - posAfter.x) * headRatio,
            posAfter.y + (pos.y - posAfter.y) * headRatio
        );
        lenAfter = Vec2.distance(posAfter, new Vec2(shootBall.node.position.x, shootBall.node.position.y));
        
        this.drawPoint(posBefore, Color.RED);
        this.drawPoint(posAfter, Color.WHITE);

        if (lenAfter > lenBefore) {
            // log("插入到前面", targetBall.TargetIndex);
            shootBall.TargetIndex = targetBall.TargetIndex + 1;
            insertIndex += 1;
        } else {
            // log("插入到后面", targetBall.TargetIndex);
            shootBall.TargetIndex = targetBall.TargetIndex;
        }
        // 同步到链首当前进度
        shootBall.Ratio = headRatio;
        for (let i = insertIndex; i < this.ballChain.length; i++) {
            this.ballChain[i].TargetIndex += 1;
        }
        this.ballChain.splice(insertIndex, 0, shootBall);

        this.checkAndRemoveMatches(shootBall); // 检查并移除匹配
    }

     // 核心消除逻辑
    private checkAndRemoveMatches(ball:Ball) {
        const targetType = ball.type
        let insertIndex = this.ballChain.indexOf(ball);
        const matches: number[] = [insertIndex];

        // log("当前插入的球的类型", targetType);

        // 向前检测
        let pre = insertIndex - 1;
        while (pre >= 0) {
            const preBall = this.ballChain[pre];
            // log("前一个球的类型", preBall.getComponent(Ball)?.type);
            if (preBall.getComponent(Ball)?.type === targetType) {
                matches.push(pre);
                pre--;
            } else {
                break;
            }
        }

        // 向后检测
        let post = insertIndex + 1;
        while (post < this.ballChain.length) {
            const postBall = this.ballChain[post];
            // log("后一个球的类型", postBall.getComponent(Ball)?.type);
            if (postBall.getComponent(Ball)?.type === targetType) {
                matches.push(post);
                post++;
            } else {
                break;
            }
        }

        // 执行消除
        if (matches.length >= 3) {
            this.handleCombo(matches.length);
            //audio

            matches.sort((a, b) => b - a); // 倒序删除避免索引错位

            matches.forEach(index => {
                const ballNode = this.ballChain.splice(index, 1)[0];
                ballNode.getComponent(Ball)?.explode(); // 播放爆炸特效
            });

            // this.fillGaps(matches[0], matches[matches.length - 1]); // 填补空隙
            return true;
        }
        return false;
    }

    // 组合得分逻辑
    private handleCombo(count: number) {
        // const now = Date.now();
        // if (now - this.comboTimer < 800) {
        //     this.combo = Math.min(this.combo + 1, 7); // 最大7连击
        // } else {
        //     this.combo = 1;
        // }
        // this.comboTimer = now;
    }

    protected update(dt: number) {
        if (this.ballChain.length === 0) return;
        this.moveHeadBall(dt);
    }

    //移动首球
    public async moveHeadBall(dt) {
        if (this.ballChain.length === 0) return;

        const head = this.ballChain[0];
        await head.moveByUpDate(dt);

        for (let i = 1; i < this.ballChain.length; i++) {
            const ball = this.ballChain[i];
            log("正确",ball.TargetIndex ,"!!!", head.TargetIndex+i)
            if(ball.TargetIndex>head.TargetIndex+i){
                continue;
            }
            ball.moveByRatio(head.Ratio,head.TargetIndex+i)
        }
        log("--------------");
        
    }
     // 新增方法：获取链首小球的实时路径进度
    public get headProgress(): { index: number, ratio: number } {
        if (this.ballChain.length === 0) return { index: -1, ratio: 0 };
        const head = this.ballChain[0];
        return { index: head.TargetIndex, ratio: head.Ratio };
    }

    // 随机生成小球颜色
    private randomColor(): BallColor {
        return Math.floor(Math.random() * 3) as BallColor; // 6种颜色
    }

    // 创建新小球
    private createBall(color?: BallColor): Ball {
        const ballNode = instantiate(this.ballPrefab);
        const ball = ballNode.getComponent(Ball)

        ballNode.setParent(this.node)
        ballNode.position = PathManager.Instance.getStartPoint()
        ball.init((color? color: this.randomColor()));
        return ball;
    }

    // 向球链头部添加小球（滚入效果）
    public addBallToChain() {
        const head = this.createBall();
        head.TargetIndex = 0;
        this.ballChain.unshift(head);
        // for (let i = 1; i < this.ballChain.length; i++) {
        //     const ball = this.ballChain[i];
        //     ball.TargetIndex = head.TargetIndex + i;
        // }
    }

    // 移除球链中的小球（消除逻辑）
    public removeBall(ball: Ball) {
        const index = this.ballChain.indexOf(ball);
        if (index !== -1) {
            this.ballChain.splice(index, 1);
            ball.explode();
        }
    }

    //test
    drawPoint(position: Vec2, color = Color.RED) {
        const pointSize = 10;
        this.graphics.fillColor = color;
        this.graphics.rect(position.x - pointSize / 2, position.y - pointSize / 2, pointSize, pointSize);
        // log("绘制点", position);
        this.graphics.fill();
    }
}